package com.guodexian.service.impl;

import com.guodexian.config.QiNiuConfig;
import com.guodexian.service.FileService;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * 类说明：<br>
 *
 * @author qfrx<br>
 * 2024/12/27 11:41<br>
 * @since 1.0 <br>
 */
@Service
public class QiNiuFileServiceImpl implements FileService {
    @Autowired
    private QiNiuConfig qiNiuConfig;

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        Configuration configuration = new Configuration(Region.autoRegion());
        UploadManager uploadManager = new UploadManager(configuration);
        Response response=uploadManager.put(file.getInputStream(),genRandomFileName(Objects.requireNonNull(file.getOriginalFilename())),getToken(),null, null);
        return response.bodyString();
    }
    private String getToken() {
        return  Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey()).uploadToken(qiNiuConfig.getBucketName());
    }
    private String  genRandomFileName(String originalFileName) {
        //a.b.c.txt
        int index = originalFileName.lastIndexOf(".");
        return UUID.randomUUID()+"." +originalFileName.substring(index+1).toLowerCase();
    }
}
